// pages/model/model.js
//index.js
var app = getApp();
var page = undefined;
var touchDot = 0;//触摸时的原点
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image: ['/image/bg1.jpg', '/image/bg2.jpg', '/image/bg3.jpg'],
    length: 3,//模板中图片的长度
    show: 1,//当前显示的图片，从1开始
    showBtn: false,
    showloading: false,
    first: true,
    animationData: {},
    up: true,
    video: false,
    music: false,
    money_change: true,
    money_num: parseFloat(0).toFixed(2),
    doommData: [],//弹幕
    comment: [],//评论内容
    like:false,
    come:true,
    switch:true,
    tanmutext:'弹'
  },

  changeMoney: function(){
    this.setData({
      money_change: false,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var res = wx.getSystemInfoSync();
    that.setData({
      width: res.screenWidth,
      height: res.screenHeight,
      options:options
    })
    page = that;
    that.getData();
    if(that.data.options.from==undefined){
      that.getcomment();
    }
    wx.getUserInfo({
      success: function (res) {
        that.setData({
          nickName:res.userInfo.nickName,
          avatarUrl:res.userInfo.avatarUrl
        })
      }
    })
  },
  getData:function(res){
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/Card/get',
        data:{
          t_session:session,
          id:that.data.options.id
        },
        success: function (res) {
          var res = res.data;
          if (res.done) {
            var data = res.retval;
            that.setData({
              data: data,
              loading: false
            })
            that.music();
          } else {
            that.setData({
              errorTips: '接口请求失败',
              loading: true
            })
          }
        },
        fail: function (res) {
          that.setData({
            errorTips: '接口请求失败',
            loading: true
          })
        }
      })
    })
  },
  onShow: function () {
    if (this.data.come != true) {
      this.music();
    } else {
      this.setData({
        come: false
      })
    }
  },
  music: function (res) {
    this.audioCtx = wx.createAudioContext('myAudio')
    this.audioCtx.setSrc(this.data.data.audio)
    this.audioCtx.play()
    this.videoContext = wx.createVideoContext('myVideo')
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function (res) {
    this.audioPause();
    this.videoPause();
  },
  audioPause: function () {
    this.audioCtx.pause()
  },
  videoPause: function () {
    this.videoContext.pause()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.nickName+'给您送来了祝福',
      path: '/pages/cart/cart?id='+that.data.options.id,
      success: function (res) {
        console.log("sres");
        app.getLoginSession(function (session) {
          wx.request({
            url: app.api +'/user/song',
            data:{
              t_session:session,
              card_id: that.data.options.id
            },
            success:function(res){
              console.log(res);
            }
          })
        })
      },
      fail: function (res) {
      }
    }
  },
  //获取评论
  getcomment:function(res){
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/shangchang/cardCommentList',
        data:{
          t_session:session,
          card_id:that.data.options.id
        },
        success:function(res){
          var res = res.data;
          if(res.done&&res.retval.length>0){
              that.setData({
                comment:res.retval
              })
              that.tanmu();
          }
        }
      })
  })
  },
  // 触摸开始事件
  touchStart: function (e) {
    var that = this;
    touchDot = e.touches[0].pageY; // 获取触摸时的原点
    if (that.data.first == true) {
      that.setData({
        first: false
      })
    }
  },
  // 触摸结束事件
  touchEnd: function (e) {
    var that = this;
    var touchMove = e.changedTouches[0].pageY;
    console.log(touchMove);
    // 向上滑动，下一页   
    if (touchDot - touchMove >= 10) {
      if (that.data.length > that.data.show) {
        if (that.data.pinglun != true && that.data.dashang != true){
          that.setData({
            show: that.data.show + 1,
            first: false,
            up: true
          })
          console.log(that.data.show);
        }
        
        // var animation = wx.createAnimation({
        //   transformOrigin: "50% 50%",
        //   duration: 1000,
        //   timingFunction: "ease",
        //   delay: 0
        // })
        // this.animation = animation
        // animation.translate(0,-603).step()

        // this.setData({
        //   animationData: animation.export()
        // })
      }
    }
    // 向下滑滑动，上一页
    if (touchMove - touchDot >= 10) {
      console.log("上一页");
      if (that.data.show > 1) {
        that.setData({
          show: that.data.show - 1
        })
      }
    }
  },
  //选择图片或者视频
  select: function (res) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '您可选择上传视频或者图片',
      cancelText: '上传视频',
      confirmText: '上传图片',
      success: function (res) {
        if (res.confirm) {
          wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              var tempFilePaths = res.tempFilePaths[0]
              that.setData({
                img: tempFilePaths
              })
            }
          })
        } else {
          wx.chooseVideo({
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            camera: 'back',
            success: function (res) {
              console.log(res);
              that.setData({
                src: res.tempFilePath,
                video: true
              })
            }
          })
        }

      }
    })
  },
  //播放、暂停
  start: function (res) {
    var that = this;
    console.log(res);
    that.setData({
      music: true
    })
  },
  stop: function () {
    var that = this;
    that.setData({
      music: false
    })
  },
  //显示底部按钮
  showBtn:function(res){
    if (this.data.options.from != 'model') {
      var show = res.currentTarget.dataset.show;
      this.setData({
        showBtn: show,
        showloading: true,
      })
    }
  },
  //显示评论框
  show_comment:function(res){
    var that = this;
    that.setData({
      pinglun:true
    })
  },
  //隐藏评论框
  hide_comment:function(res){
    var that = this;
    that.setData({
      pinglun: false
    })
  },
  //显示评论框
  show_reward: function (res) {
    var that = this;
    that.setData({
      dashang: true
    })
  },
  //隐藏评论框
  hide_reward: function (res) {
    var that = this;
    if (res.currentTarget.dataset.show){
      that.setData({
        dashang: false,
      })
    }
    else{
      if (that.data.money_num == undefined || that.data.money_num == "" || !/^\d+(\.\d+)?$/.test(that.data.money_num)||that.data.money_num==0) {
        wx.showToast({
          title: '请输入正确数额',
        })
        that.setData({
          money_num: parseFloat(0).toFixed(2),
        })
        return;
      }
      else if (that.data.money_num > 0 ){
        that.setData({
          money_change: true,
          money_num: parseFloat(that.data.money_num).toFixed(2),
        })
      }
    }
  },
  //点击遮罩层，隐藏
  hide:function(res){
    var that = this;
    that.setData({
      pinglun:false,
      dashang:false
    })
  },
  //获取用户输入
  input:function(res){
    var that = this;
    var value = res.detail.value;
    var type= res.currentTarget.dataset.type;
    console.log(res);
    if (type =="comment"){
      console.log(value);
      that.setData({
        value:value
      })
    }else{
      that.setData({
        money_num: value,
      })
    }
  },
  //提交评论
  submit_comment:function(res){
    var that = this;
    if(that.data.value==undefined||that.data.value==""){
      wx.showModal({
        title: '提示',
        content: '请输入评论内容',
      })
    }else{
      that.setData({
        pinglun:false
      })
      app.getLoginSession(function (session) {
        wx.request({
          url: app.api +'/Shangchang/addComment',
          data:{
            card_id: that.data.options.id,
            content:that.data.value,
            t_session:session
          },
          success:function(res){
            var res = res.data;
            if(res.done){
              wx.showToast({
                title: '评论成功！',
              })
              var comment = that.data.comment;
              comment.push({
                photo: that.data.avatarUrl,
                concent: that.data.value
              })
              that.setData({
                comment:comment
              })
              
            }else{
              wx.showModal({
                title: '提示',
                content: res.msg,
              })
            }
          },
          fail:function(res){
            wx.showToast({
              title: '失败，请重试！',
            })
          }
        })
    })
    }
  },
  btn_money:function(res){
    var money = res.currentTarget.dataset.money;
    var that = this;
    that.setData({
      money_change: false,
      money_num: parseFloat(money).toFixed(2),
    })
  },
  //提交打赏金额
  submit_reward: function (res) {
    var that = this;
    console.log(that.data.money_num);
    that.setData({
      dashang: false
    })
    wx.showModal({
      title: '温馨提示',
      content: '您将打赏'+that.data.money_num+'元给您好友。',
      success: function (res) {
        if (res.confirm) {
          app.getLoginSession(function (session) {
            wx.request({
              url: app.api +'/Payment/pay_now?card_id=2&price=12.5',
              data:{
                card_id: that.data.options.id,
                price:that.data.money_num,
                t_session:session
              },
              success:function(res){
                var res = res.data;
                if(res.done){
                  app.callToPay(parseInt(res.retval.order_id));
                }
              }
            })
        })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }  
    })
  },
  //点赞
  lick:function(res){
    var that = this;
    if(that.data.like==false){
      app.getLoginSession(function (session) {
        wx.request({
          url: app.api + '/shangchang/addZan',
          data:{
            t_session:session,
            card_id:that.data.options.id
          },
          success:function(res){
            var res = res.data;
            if(res.done){
              that.setData({
                like:true
              })
            }else{
              wx.showToast({
                title: '请重试！',
              })
            }
          },
          fail:function(res){
            wx.showToast({
              title: '请重试！',
            })
          }
        })
    })
    }else{
      app.getLoginSession(function (session) {
        wx.request({
          url: app.api + '/shangchang/cancelZan',
          data:{
            t_session:session,
            card_id:that.data.options.id
          },
          success: function (res) {
            var res = res.data;
            if (res.done) {
              that.setData({
                like: false
              })
            } else {
              wx.showToast({
                title: '请重试！',
              })
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '请重试！',
            })
          }
        })
      })
    }
  },
   //弹幕
  tanmu: function () {
    var that = this;
    console.log("弹幕");
    that.setData({
      doommData: [],
      doommList: []
    })
    doommList = []
    console.log(that.data.comment);
    for (var i = 0; i < that.data.comment.length; i++) {
      if(that.data.comment[i].concent!=''){
        console.log(that.data.comment);
        doommList.push(new Doomm(that.data.comment[i].concent, Math.ceil(Math.random() * 100), Math.ceil(Math.random() * 10) + 10, getRandomColor(), that.data.comment[i].photo));
        that.setData({
          doommData: doommList
        })
        if (i == that.data.comment.length - 1) {
          console.log(that.data.doommData);
          setTimeout(function () {
            that.tanmu();
          }, 10000)
        }
      }
      
    }
  },
  //返回编辑
  leftBtn:function(res){
    wx.navigateBack({
      delta:1
    })
  },
  //我也要做
  rightBtn:function(res){
    var that = this;
    wx.navigateTo({
      url: '/pages/model/model?id='+that.data.data.id,
    })
  },
  //弹幕开关
  switch:function(res){
    var that = this;
    if(that.data.switch==true){
      that.setData({
        doommData: [],
        doommList: [],
        switch:false,
        tanmutext:'关'
      })
    }else{
      that.tanmu();
      that.setData({
        switch: true,
        tanmutext: '弹'
      })
    }
  }
})
var doommList = [];
var i = 0;
class Doomm {
  constructor(text, top, time, color,img) {
    this.text = text;
    this.top = top;
    this.time = time;
    this.color = color;
    this.display = true;
    let that = this;
    this.id = i++;
    this.img = img
    setTimeout(function () {
      page.setData({
        doommData: doommList
      })
    }, this.time * 1000)
  }
}
function getRandomColor() {
  let rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}